#include "nettools.h"
#include <QTest>

NetTools::NetTools(QObject *parent) :
    QObject(parent)
{
    _webs.insert("dyndns","http://checkip.dyndns.org/index.php/");
    _webs.insert("whatismyip.","http://automation.whatismyip.com/n09230945.asp");
    _webs.insert("freeshell","http://cfaj.freeshell.org/ipaddr.cgi");
    _webs.insert("informaction","https://secure.informaction.com/ipecho");
    _webs.insert("icanhazip","http://icanhazip.com");
    _webs.insert("no-ip","http://ip1.dynupdate.no-ip.com/");
}

QString NetTools::GetIp(QString metod)
{

    QString ret="";
    QRegExp rx("(\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3})");
    if(metod.compare("dyndns")==0 || metod.compare("no-ip")==0){
        ret = gethtml(_webs["dyndns"]);
        rx.indexIn(ret, 0);
        _WanIp=rx.cap(0);
    }else if(metod.compare("whatismyip")==0){
        ret = gethtml(_webs["dyndns"]);
    }else if(metod.compare("freeshell")==0){
        ret = gethtml(_webs["dyndns"]);
    }else if(metod.compare("informaction")==0){
        ret = gethtml(_webs["dyndns"]);
    }else if(metod.compare("icanhazip")==0){
        ret = gethtml(_webs["dyndns"]);
    }

    return _WanIp;

}

QList<QString>  NetTools::GetMetods()
{
    return _webs.keys();
}

QString NetTools::gethtml(QString url){
    _http = new QHttp;
    _Kip=false;
    connect(_http,SIGNAL(done(bool)),this,SLOT(getdone(bool)));
    QUrl httpurl(url);
    _http->setHost(httpurl.host(), httpurl.port(80));
    _http->get(httpurl.path());

    while(!_Kip){
       QTest::qWait ( 1 );
    }

    QString ret(_http->readAll());
    return ret;
}
void NetTools::getdone(bool)
{
    _Kip=true;
}
